<?php defined('BASEPATH') || exit('No direct script access allowed');

use EasyWeChat\Foundation\Application;
use Grafika\Grafika;
use Grafika\Color;
/**
 *  controller 仅作为小型活动处理
 */
class Report extends Front_Controller
{

    private $_sessionUserKey = 'jinrong_user_login';
    private $_urlMiddle = 'report';
    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
        $this->load->library('user_agent');
        $this->load->model('mohe/financesources_model');
        $this->load->model('Activityfinanceregister_model');
        $this->load->model('mohe/financesources_model');
    }

    public function index(){
        redirect('/');
        exit();
        if (!$this->session->has_userdata('loginInfo')) {
            redirect('/report/login');
        }
        $logined = $this->session->userdata('loginInfo');
        if($logined['user'] != "admin"){
            redirect('/report/data');
        }
        $page = $this->input->get("page");
        $page = isset($page) ? $page : 1;
        $currentQuery = "";
        // 获取一级渠道
        $parentSource = $this->financesources_model->where("deleted = 0 and parent_id = 0")->find_all();
        $data['parentSource'] = $parentSource;
        // 获取登录账户的子渠道
        $logined = $this->session->userdata('loginInfo');
        if($logined['user'] != "admin"){
            $parentArr = $this->financesources_model->find_by(['code'=>$logined['user']]);
            $parent_id = $parentArr->id;
            $sonSource = $this->financesources_model->where("deleted = 0 and parent_id = $parent_id")->find_all();
            $data['sonSource'] = $sonSource;
        }
        $data['username'] = $logined['user'];
        // 获取注册号码
        $registerTable = $this->Activityfinanceregister_model->get_table();
        $sourcesTable = $this->financesources_model->get_table();
        $where = "1 = 1";
        $get = $this->input->get();
        if(!empty($get['p_id'])){
            $query['p_id'] = $get['p_id'];
            $slist = $this->financesources_model->where("parent_id = ".$get['p_id'])->find_all();
            $str = "(";
            if($slist){
                foreach ($slist as $key=>$value) {
                    $str .= $value->id.",";
                }
                $data['slist'] = $slist;
            }
            $str .= $get['p_id'];
//            $str = substr($str,0,strlen($str)-1);
            $str .= ")";
            $where .= " and source in $str";
            $data['p_id'] = $get['p_id'];
        }
        if(!empty($get['s_id'])){
            $where .= " and source = ".$get['s_id'];
            $data['s_id'] = $get['s_id'];
            $query['s_id'] = $get['s_id'];
        }
        $currentQuery = !empty($query) ? http_build_query($query) : "";
        // 分页
        $totalRows = $this->Activityfinanceregister_model->where($where)->count_all();
        $pagerUriSegment = 6;
        $pagerBaseUrl = site_url('/report/index');
        $limit  = $this->settings_lib->item('site.list_limit') ?: 15;
        $offset = ($page-1)*$limit;
        $this->load->library('pagination');
        $this->pager['base_url']    = $pagerBaseUrl."?".$currentQuery;
        $this->pager['total_rows']  = $totalRows;
        $this->pager['per_page']    = $limit;
        $this->pager['use_page_numbers'] = true;
        $this->pager['page_query_string'] = true;
        $this->pager['enable_query_strings'] = true;
        $this->pager['query_string_segment'] = 'page';
        $this->pager['uri_segment'] = $pagerUriSegment;
        $this->pagination->initialize($this->pager);
        $this->Activityfinanceregister_model->limit($limit, $offset);
//        echo $this->pagination->create_links();exit();
        $source = $this->Activityfinanceregister_model->where($where)->join($sourcesTable, "{$registerTable}.source = {$sourcesTable}.id", 'left')->order_by("createtime",'desc')->find_all();
        $data['source'] = $source;
        $this->load->view('report/index', $data);
    }

    public function ajax_source_data() {
        $parentID = $this->input->get('p_id');
        $data = $this->financesources_model->where("parent_id = $parentID")->find_all();
        $html = '<option selected="selected" value="0">可选择</option>';
        if (!empty($data)) {
            foreach ($data as $key=>$obj) {
                $html .= '<option value="'.$obj->id.'">'.$obj->name.'</option>';
            }
        }
        echo $html;
    }

    public function login(){
        // 入口关停8.28
        redirect('/');
        exit();
        $post = $this->input->post();
        if(!empty($post)){
            $account = $post['account'];
            $password = $post['password'];
            if(!empty($account) && !empty($password)){
                // 管理员登录
                if($account == 'admin' && $password == 'usure500'){
                    $userInfo = ['user'=>$account,'isLogin'=>1];
                    $this->session->set_userdata('loginInfo', $userInfo);
                    echo json_encode(['status'=>1,'errMsg'=>'登录成功']);exit();
                }
                // 普通用户登录
                $parentSource = $this->financesources_model->where("deleted = 0 and parent_id = 0")->find_all();
                if(!empty($parentSource)){
                    foreach ($parentSource as $key=>$obj) {
                        $users[] = $obj->code;
                    }
                    if(in_array($account, $users) && $password == $account."123"){
                        $userInfo = ['user'=>$account,'isLogin'=>1];
                        $this->session->set_userdata('loginInfo', $userInfo);
                        echo json_encode(['status'=>1,'errMsg'=>'登录成功']);exit();
                    }else{
                        echo json_encode(['status'=>0,'errMsg'=>'账号或密码错误']);exit();
                    }
                }else{
                    echo json_encode(['status'=>0,'errMsg'=>'请使用管理员账户登录']);exit();
                }

            }else{
                echo json_encode(['status'=>0,'errMsg'=>'账号或密码为空']);exit();
            }
        }else{
            $data = [];
            $this->load->view('report/login', $data);
        }
    }

    public function sessions() {
        dump($this->session->userdata());
        echo APPPATH.'cache/ci3_sessions';
    }

    public function logout(){
        $this->session->unset_userdata('loginInfo');
        redirect('/report/index');
    }

    public function data(){
        redirect('/');
        exit();
        if (!$this->session->has_userdata('loginInfo')) {
            redirect('/report/login');
        }
        // 获取一级渠道
        $parentSource = $this->financesources_model->where("deleted = 0 and parent_id = 0")->find_all();
        $data['parentSource'] = $parentSource;
        // 获取登录账户的子渠道
        $logined = $this->session->userdata('loginInfo');
        if($logined['user'] != "admin"){
            $parentArr = $this->financesources_model->find_by(['code'=>$logined['user']]);
            $parent_id = $parentArr->id;
            $sonSource = $this->financesources_model->where("deleted = 0 and parent_id = $parent_id")->find_all();
            $data['sonSource'] = $sonSource;
            // 获取登录用户的一级渠道
            $code = $logined['user'];
            $parentSource = $this->financesources_model->where("deleted = 0 and code = '$code'")->find_all();
            $data['parentSource'] = $parentSource;
        }
//        dump($data);exit();
        $thisWeekStart = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
        $thisWeekEnd = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
        $thisMonthStart = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
        $thisMonthEnd = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

        $registerTable = $this->Activityfinanceregister_model->get_table();
        $jrWhere = "$registerTable.createtime >= '".date("Y-m-d 00:00:00")."' AND $registerTable.createtime <= '".date("Y-m-d 23:59:59")."'";
        $zrWhere = "$registerTable.createtime >= '".date("Y-m-d 00:00:00", strtotime("-1 day"))."' AND $registerTable.createtime <= '".date("Y-m-d 23:59:59", strtotime("-1 day"))."'";
        $bzWhere = "$registerTable.createtime >= '".$thisWeekStart."' AND $registerTable.createtime <= '".$thisWeekEnd."'";
        $byWhere = "$registerTable.createtime >= '".$thisMonthStart."' AND $registerTable.createtime <= '".$thisMonthEnd."'";
        $ljWhere = "1 = 1";
        // 数据
        $data['jr'] = $this->getCount($jrWhere);
        $data['zr'] = $this->getCount($zrWhere);
        $data['bz'] = $this->getCount($bzWhere);
        $data['by'] = $this->getCount($byWhere);
        $data['lj'] = $this->getCount($ljWhere);
        // 获取登录账户的子渠道
        $logined = $this->session->userdata('loginInfo');
        $data['username'] = $logined['user'];
        $this->load->view('report/main', $data);
    }

    /**
     * 日期查询
     */
    public function getDataByDate(){
        $post = $this->input->post();
        $start = !empty($post['start']) ? $post['start']." 00:00:00" : "";
        $end = !empty($post['end']) ? $post['end']." 23:59:59": "";
        $p_id = !empty($post['p_id']) ? $post['p_id'] : "";
        $s_id = !empty($post['s_id']) ? $post['s_id'] : "";
        $registerTable = $this->Activityfinanceregister_model->get_table();
        $where = "checked = 1";
        if($start && $end){
            $where .= " AND $registerTable.createtime >= '".$start."' AND $registerTable.createtime <= '".$end."'";
        }
        if($p_id){
            $slist = $this->financesources_model->where("parent_id = $p_id")->find_all();
            $str = "(";
            if($slist){
                foreach ($slist as $key=>$value) {
                    $str .= $value->id.",";
                }
            }
            $str .= $p_id;
//            $str = substr($str,0,strlen($str)-1);
            $str .= ")";
            $where .= " AND source in $str";
            if($s_id){
                $where .= " AND source = $s_id";
            }
        }
        $num = $this->getCount($where);
        $reback = json_encode(['num'=>$num,'start'=>$start,'end'=>$end]);
        echo $reback;exit();
    }
    private function getCount($where, $group = ''){
        $where .= " AND checked = 1";
        // 根据登录用户拼接条件
        $logined = $this->session->userdata('loginInfo');
        if($logined['user'] != "admin"){
            $parentArr = $this->financesources_model->find_by(['code'=>$logined['user']]);
            $p_id = $parentArr->id;
            $slist = $this->financesources_model->where("parent_id = $p_id")->find_all();
            $str = "(";
            if($slist){
                foreach ($slist as $key=>$value) {
                    $str .= $value->id.",";
                }
            }
            $str .= $p_id;
            $str .= ")";
            $where .= " AND source in $str";
        }
        if(!empty($group)){
            return $this->Activityfinanceregister_model->where($where)->group_by($group)->count_all();
        }else{
            return $this->Activityfinanceregister_model->where($where)->count_all();
        }
    }

    public function sendSmsNew(){
        $get = $this->input->get();
        if(!empty($get['mobile'])){
            $mobile = $get['mobile'];
            $post_url = "http://sms.10690221.com:9011/hy/";
            $smsData = array(
                'uid'=>'506995',
                'auth'=>md5('xacssioo05'),
                'mobile'=>$mobile,
                'msg'=>urlencode("您的验证码为:123456"),
                'expid'=>0,
                'encode'=>'utf-8'
            );
            $this->load->library('curl', $post_url);
            $this->curl->post($smsData);
            $returnStr = $this->curl->execute();
            if (!empty($returnStr) && stripos($returnStr, ',') !== false) {
                echo "发送成功";
            }else{
                echo "发送失败";
            }
            dump($returnStr);
        }else{
            echo "号码不能为空";
        }
    }
    public function sendSmsQxt(){
        $get = $this->input->get();
        if(!empty($get['mobile'])){
            $mobile = $get['mobile'];
            $post_url = "http://112.90.92.219:8811/sms.aspx";
            $smsData = array(
                'userid'=>'451',
                'account'=>'1069034023',
                'password'=>'a123456',
                'mobile'=>$mobile,
                'content'=>"【测试】验证码1234",
                'action'=>'send'
            );
            $this->load->library('curl', $post_url);
            $this->curl->post($smsData);
            $returnStr = $this->curl->execute();
            if (!empty($returnStr)) {
                $obj = simplexml_load_string($returnStr);
            }
            dump($obj);
        }else{
            echo "号码不能为空";
        }
    }
}